#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
using namespace std;

void SetNonBlock(int fd)
{
    int flag = fcntl(fd, F_GETFL, 0);
    if(flag < 0)
    {
        cout << "fcntl error" << endl;
        return;
    }

    fcntl(fd, F_SETFL, flag | O_NONBLOCK);
}

int main()
{
    SetNonBlock(0);

    char buffer[1024];
    while(1)
    {

        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if(n > 0) 
        {
            buffer[n] = '0';
            cout << "message : " << buffer << endl;
        }
        else if(n == 0)
        {
            cout << "读取结束" << endl;
        }
        else
        {
            if(errno == 11)
            {
                cout << "资源没有就绪 非阻塞轮询" << endl; 
                printf("errno : %d, err string : %c\n", errno, strerror(errno));
            }
            else 
            {
                cout << "读取出错" << endl; 
                printf("errno : %d, err string : %s \n", errno, strerror(errno));
                break;
            }
        }
        
        sleep(1);

    }
    return 0;
}